package com.banciyuan.bcywebview.biz.zanlist;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.detail.goods.GoodsDetailActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.DetailGoods;

public class GoodsZanListFragment extends BaseLazyContainerFragment {
    private List<DetailGoods> list = new ArrayList<>();
    private GoodsZanAdapter adapter;
    private PullToRefreshListView refreshableView;
    private ListView lv;
    private String sub = "zhipin";
    private LoadingHelper mProgressbarHelper;
    private RequestQueue mQueue;
    private boolean loading = false;
    private boolean hasMore = true;
    private int page = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.novel_layout, container, false);
        initProgressbar(rootView);
        initArgs();
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    protected void initUi(View rootview) {
        refreshableView = (PullToRefreshListView) rootview.findViewById(R.id.refresh_lv);
        lv = refreshableView.getRefreshableView();

        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dip2px(8, getActivity()));
        View view = new View(getActivity());
        view.setLayoutParams(layoutParams);
        lv.addHeaderView(view);
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
        Bundle bundle = getArguments();
        sub = bundle.getString("sub");
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarHelper = new LoadingHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                hasMore = true;
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initAction() {
        refreshableView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && hasMore) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        refreshableView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    loading = true;
                    hasMore = true;
                    page = 1;
                    initData();
                }
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    i = i - 2;
                    DetailGoods detailGoods = list.get(i);
                    if (null != detailGoods) {
                        gotoUtil.gotoAct(getActivity(), GoodsDetailActivity.class, detailGoods.getZg_id());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        paramsList.add(new BcyPair(HttpUtils.COMENT_SUB, sub));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        paramsList.add(new BcyPair(HttpUtils.LIMIT, "10"));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + SpaceApi.getZanlist();

        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                processData(s);
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onDataError();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), params);
        StringRequest stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSuccess, errorProxy);
        mQueue.add(stringRequest);
    }

    protected void processData(String s) {
        Gson gson = new Gson();
        try {
            if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                JSONObject result = new JSONObject(s);
                List<DetailGoods> tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA),
                        new TypeToken<List<DetailGoods>>() {
                        }.getType());
                if (tempList.size() == 0) {
                    onDataEmpty();
                } else {
                    processGoodsData(tempList);
                }
            } else {
                onDataError();
            }
        } catch (Exception e) {
            onDataError();
        }
    }

    private void processGoodsData(List<DetailGoods> tempList) {
        resetData();
        list.addAll(tempList);
        if (null == adapter) {
            adapter = new GoodsZanAdapter(getActivity(), list);
            lv.setAdapter(adapter);
        } else {
            adapter.setData(list);
            adapter.notifyDataSetChanged();
        }
        onDataSuccess();
    }

    protected void resetData() {
        if (page == 1) {
            list.clear();
        }
    }

    protected void onDataSuccess() {
        loading = false;
        mProgressbarHelper.onSuccess();
        refreshableView.onRefreshComplete();
    }

    protected void onDataError() {
        loading = false;
        mProgressbarHelper.onFailed();
        refreshableView.onRefreshComplete();
    }

    protected void onDataEmpty() {
        if (page == 1) {
            mProgressbarHelper.onNodata("", true);
        }
        loading = false;
        hasMore = false;
        refreshableView.onRefreshComplete();
    }
}
